package com.seamtop.cuber.web.service.impl;

import com.seamtop.cuber.common.base.DataObject;
import com.seamtop.cuber.common.base.ParseUtil;
import com.seamtop.cuber.common.entriy.ErrorCode;
import com.seamtop.cuber.common.entriy.Validator;
import com.seamtop.cuber.common.exception.CuberFileParseException;
import com.seamtop.cuber.web.service.ValidateService;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;

/**
 * Created by feng on 2015/11/6.
 */
@Service
public class ValidateServiceImpl implements ValidateService {

    public void loadCuberValidators(){
        String path = this.getClass().getClassLoader().getResource("").getPath();
        try{
            Document document = loadCuberValidators(path);
            HashMap<String,Validator> validatorHashMap = ParseUtil.parseValidateMap(document);
            DataObject.setCuberValidatorMap(validatorHashMap);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public Document loadCuberValidators(String path) throws Exception{
        String fileName = "params_validate.xml";
        InputStream is = null;
        try{
            is = new FileInputStream(new File(path + fileName));
        }catch (Exception e){
            throw new CuberFileParseException(new ErrorCode(ErrorCode.FILE_LOAD_ERROR, fileName).toString());
        }
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(is);
        return document;
    }
}
